<?php
namespace app\index\controller\dictionary;
use app\index\controller\BaseIndex;
use szktor\ClinicDict; //诊所门店公共字典
use app\common\model\ClinicDictsheet; //字典表数据
use app\common\model\SystemDrug; //系统西药信息表

/*
* 前台-字典维护 -> 药品/材料
* index/dictionary.drugs/index
*/
class Drugs extends BaseIndex
{
    protected $noNeedLogin = [];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = ['info','del','find_sysdrug','find_clinic_drug']; //无需鉴权的方法，但需要登录

    //首页
    public function index()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            try
            {
                $data = $this->request->only(['dicttype','keyword','status','page'],'post');
                if(!isset($data['dicttype']))
                {
                    return json(['code' => '1', 'msg' => '参数错误，无法获取数据', 'count' => '0', 'data' => []]);
                }
                $data['dicttype'] = strtolower($data['dicttype']);
                if($data['dicttype'] == 'xy')
                {
                    //西药数据--获取列表
                    return $this->xiYaoList($data);
                }
                if($data['dicttype'] == 'zy')
                {
                    //中药数据--获取列表
                    return $this->zhongYaoList($data);
                }
                if($data['dicttype'] == 'cl')
                {
                    //材料数据--获取列表
                    return $this->caiLiaoList($data);
                }
                return json(['code' => '1', 'msg' => '参数错误，无法获取数据', 'count' => '0', 'data' => []]);
            }catch (\think\Exception $e){ // use think\Exception;
               return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
            }
        }
		$this->assign([
            'xy_yptype_list' => ClinicDict::getDrugsTypeList(), //西药 - 药品类型
            'xy_jlunit_list' => ClinicDict::getDrugsJiLiangUnitList(), //西药 - 剂量单位
            'xy_zjunit_list' => ClinicDict::getDrugsZhiJiUnitList(), //西药 - 制剂单位
            'xy_kcunit_list' => ClinicDict::getDrugsKuCunUnitList(), //西药 - 库存单位
            'xy_yongfa_list' => ClinicDict::getZhuSheDanLaiYuanList(), //西药 - 默认用法
            'xy_yypl_list' => ClinicDict::getXiYaoPinLvList(), //西药 - 用药频率
            'zy_yptype_list' => ClinicDict::getZyDrugsTypeList(), //中药 - 药品类型
            'cl_type_list' => ClinicDict::getCaiLiaoCateList(), //材料 - 材料类型
            'cd_type_list' => ClinicDict::getChanDiTypeList(), //产地
            'zy_unit_list' => ClinicDict::getZhongYaoUnitList(), //中药(销售单位+库存单位)、材料(最小单位+库存单位)
        ]);
        return $this->view->fetch();
    }
    //修改 + 新增
    public function info()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $data = $this->request->only(['dicttype'],'post');
            if(!isset($data['dicttype']))
            {
                return json(['err' => '1', 'msg' => '参数错误，无法执行']);
            }
            if($data['dicttype'] == 'xy')
            {
                //西药数据--修改+增加
                return $this->xiYaoListInfo();
            }
            if($data['dicttype'] == 'zy')
            {
                //中药数据--修改+增加
                return $this->zhongYaoListInfo();
            }
            if($data['dicttype'] == 'cl')
            {
                //材料数据--修改+增加
                return $this->caiLiaoListInfo();
            }
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
    //删除
    public function del()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $data = $this->request->only(['dicttype','id'],'post');
            if(!isset($data['dicttype']))
            {
                return json(['err' => '1', 'msg' => '参数错误，无法执行']);
            }
            $r = false;
            $map = [['id','in',$data['id']],['clinic_id','=',$this->admin['clinic_id']]];
            if($data['dicttype'] == 'xy')
            {
                //西药数据--删除
                $map[] = ['drugs_type','=','0']; //类型,0=西药,1=中药,2=材料
                $r = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)->delete();
            }
            if($data['dicttype'] == 'zy')
            {
                //中药数据--删除
                $map[] = ['drugs_type','=','1']; //类型,0=西药,1=中药,2=材料
                $r = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)->delete();
            }
            if($data['dicttype'] == 'cl')
            {
                //材料数据--删除
                $map[] = ['drugs_type','=','2']; //类型,0=西药,1=中药,2=材料
                $r = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)->delete();
            }
            if(!$r) return json(['err' => '2', 'msg' => '删除失败，请重试']);
            return json(['err' => '0', 'msg' => '删除成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
    //查找系统系统西药信息表
    public function find_sysdrug()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $data = $this->request->only(['keyword','limit','page'],'post');
            if(!isset($data['page']))
            {
                return json(['err' => '2', 'msg' => '参数错误，无法获取数据']);
            }
            //条件
            $map = [['status','=', '1']];
            if(isset($data['keyword']) && $data['keyword'] != '')
            {
                $map[] = ['name|guoyaozhunzi|changjia|sn|goods_name|benweima|bianma|py_code|wb_code','like','%' . $data['keyword'] . '%'];
            }
            $limit = intval($data['limit']) > 0 ? intval($data['limit']) : 20;
            $field = 'name,spec,jixing,guoyaozhunzi,changjia,yp_type,sn,goods_name,benweima,bianma,py_code,wb_code,' .
                     'jl_num,jl_unit,zj_num,zj_unit,kc_unit,is_kjyw,mr_yl';
            $list = SystemDrug::where($map)->field($field)
                    ->order('create_time desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
            if (count($list) <= 0) {
                return json(['err' => '3', 'msg' => '当前页下无数据']);
            }
            //foreach ($list as $key => &$val) { }
            return json(['err' => '0', 'page' => $data['page'], 'limit' => $limit, 'data' => $list->items()]);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }

    //西药数据--获取列表
    private function xiYaoList($post = [])
    {
        //条件
        $map = [
            ['clinic_id','=', $this->admin['clinic_id']],
            ['drugs_type','=', '0'], //类型,0=西药,1=中药,2=材料
        ];
        $page = isset($post['page']) ? $post['page'] : 1;
        if(isset($post['keyword']) && $post['keyword'] != '')
        {
            $map[] = ['name|jixing|guoyaozhunzi|changjia|sn|goods_name|benweima|bianma|py_code|wb_code','like','%' . $post['keyword'] . '%'];
        }
        if(isset($post['status']) && $post['status'] != '')
        {
            if(strtoupper($post['status']) != 'ALL') $map[] = ['status','=',(int)$post['status']];
        }
        if(isset($post['cate_id']) && $post['cate_id'] != '')
        {
            if(strtoupper($post['cate_id']) != 'ALL') $map[] = ['cate_id','=',(int)$post['cate_id']];
        }
        $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
        $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)->field('*')
                ->order('create_time desc')->paginate($limit,false,['page' => $page, 'var_page' => 'page']);
        if (count($list) <= 0) {
            return json(['code' => '1', 'msg' => '当前页下的数据已显示完毕！', 'count' => '0', 'data' => []]);
        }
        $zhiJiArr = ClinicDict::getDrugsZhiJiUnitList(); //西药 - 制剂单位
        $xyKuCunUnitArr = ClinicDict::getDrugsKuCunUnitList(); //西药 - 库存单位
        $res = ['code' => 0,'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
        foreach ($res['data'] as $key => &$val) {
            $val['zj_unit_txt'] = _getDictNameTxt($val['zj_unit'],$zhiJiArr); //西药 - 制剂单位 
            $val['ls_unit_txt'] = _getDictNameTxt($val['kc_unit'],$xyKuCunUnitArr); //西药 - 库存单位
            $val['create_time'] = $val['create_time'] > 0 ? date('Y-m-d H:i:s',$val['create_time']) : '/';
            //is_cl = 是否拆零0.否1.是
            if((int)$val['is_cl'] <= 0)
            {
                $val['cl_price_txt'] = '未拆零';
            }else{
                $val['cl_price_txt'] = $val['cl_price'];
            }
            $val['cf_spec'] = _getXiYaoSpecText($val);
        }
        return json($res);
    }
    //中药数据--获取列表
    private function zhongYaoList($post = [])
    {
        //条件
        $map = [
            ['clinic_id','=', $this->admin['clinic_id']],
            ['drugs_type','=', '1'], //类型,0=西药,1=中药,2=材料
        ];
        $page = isset($post['page']) ? $post['page'] : 1;
        if(isset($post['keyword']) && $post['keyword'] != '')
        {
            $map[] = ['name|jd_name|changjia|benweima|bianma|py_code|wb_code','like','%' . $post['keyword'] . '%'];
        }
        if(isset($post['status']) && $post['status'] != '')
        {
            if(strtoupper($post['status']) != 'ALL') $map[] = ['status','=',(int)$post['status']];
        }
        $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
        $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)->field('*')
                ->order('create_time desc')->paginate($limit,false,['page' => $page, 'var_page' => 'page']);
        if (count($list) <= 0) {
            return json(['code' => '1', 'msg' => '当前页下的数据已显示完毕！', 'count' => '0', 'data' => []]);
        }
        $res = ['code' => 0,'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
        foreach ($res['data'] as $key => &$val) {
            $val['ls_unit_txt'] = _getDictNameTxt($val['ls_unit'],ClinicDict::getDrugsZhiJiUnitList()); //西药 - 制剂单位 
            $val['create_time'] = $val['create_time'] > 0 ? date('Y-m-d H:i:s',$val['create_time']) : '/';
        }
        return json($res);
    }
    //材料数据--获取列表
    private function caiLiaoList($post = [])
    {
        //条件
        $map = [
            ['clinic_id','=', $this->admin['clinic_id']],
            ['drugs_type','=', '2'], //类型,0=西药,1=中药,2=材料
        ];
        $page = isset($post['page']) ? $post['page'] : 1;
        if(isset($post['keyword']) && $post['keyword'] != '')
        {
            $map[] = ['name|changjia|bianma|py_code|wb_code','like','%' . $post['keyword'] . '%'];
        }
        if(isset($post['status']) && $post['status'] != '')
        {
            if(strtoupper($post['status']) != 'ALL') $map[] = ['status','=',(int)$post['status']];
        }
        $limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
        $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)->field('*')
                ->order('create_time desc')->paginate($limit,false,['page' => $page, 'var_page' => 'page']);
        if (count($list) <= 0) {
            return json(['code' => '1', 'msg' => '当前页下的数据已显示完毕！', 'count' => '0', 'data' => []]);
        }
        //中药(销售单位+库存单位)、材料(最小单位+库存单位)
        $clLsUnitArr = ClinicDict::getZhongYaoUnitList();
        //材料分类
        $clCateArr = ClinicDict::getCaiLiaoCateList();
        $res = ['code' => 0,'msg' => '', 'count' => $list->total(), 'data' => $list->items()];
        foreach ($res['data'] as $key => &$val) {
            $val['cate_id_txt'] = _getDictNameTxt($val['cate_id'],$clCateArr); //材料分类
            $val['ls_unit_txt'] = _getDictNameTxt($val['ls_unit'],$clLsUnitArr); //材料(最小单位+库存单位)
            $val['kc_unit_txt'] = _getDictNameTxt($val['kc_unit'],$clLsUnitArr); //材料(最小单位+库存单位)
            $val['create_time'] = $val['create_time'] > 0 ? date('Y-m-d H:i:s',$val['create_time']) : '/';
        }
        return json($res);
    }
    //西药数据--修改+新增
    private function xiYaoListInfo()
    {
        $data = $this->request->only([
            'dicttype','id','name','spec','jixing','guoyaozhunzi','changjia','yp_type','sn','cate_id',
            'goods_name','benweima','py_code','wb_code','bianma','jl_num','jl_unit','zj_num',
            'zj_unit','kc_unit','price','max_price','status','is_cl','cl_price','is_kjyw','mr_yf','mr_pl','mr_yl',
        ],'post');
        if(!isset($data['id']))
        {
            return json(['err' => '1', 'msg' => '参数错误，无法执行']);
        }
        $dictType = strtolower($data['dicttype']);
        unset($data['dicttype']);
        if(!isset($data['name']) || $data['name'] == '')
        {
            return json(['err' => '2', 'msg' => '必须输入一个名称']);
        }
        if(!isset($data['spec']) || $data['spec'] == '')
        {
            return json(['err' => '3', 'msg' => '必须输入规格']);
        }
        if(!isset($data['jixing']) || $data['jixing'] == '')
        {
            return json(['err' => '4', 'msg' => '必须输入剂型']);
        }
        if(!isset($data['price']) || $data['price'] == '')
        {
            return json(['err' => '5', 'msg' => '必须输入零售价']);
        }
        try
        {
            $info = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where([
                'id' => intval($data['id']), 'clinic_id' => $this->admin['clinic_id']
            ])->find();
            unset($data['id']);
            if($info) //数据已存在
            {
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where(['id' => $info['id']])->update($data);
            }else{ //数据不存在
                $sqlData = array_merge($data,[
                    'drugs_type' => '0', //类型,0=西药,1=中药,2=材料
                    'clinic_id' => $this->admin['clinic_id'], //诊所门店表的id
                    'remarks' => '', //备注
                    'create_time' => time(), //创建时间
                ]);
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->insertGetId($sqlData);
            }
            unset($data,$info,$sqlData);
            if(!$editRes) return json(['err' => '2', 'msg' => '西药数据保存失败']);
            return json(['err' => '0', 'msg' => '西药数据已保存成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '失败：' . $e->getMessage()]);
        }
    }
    //中药数据--修改+增加
    private function zhongYaoListInfo()
    {
        $data = $this->request->only([
            'dicttype','id','name','spec','jd_name','changjia','chandi','yp_type','py_code','wb_code',
            'benweima','bianma','status','ls_unit','kc_unit','kc_zh_bi','price','max_price','mr_yf',
        ],'post');
        if(!isset($data['id']))
        {
            return json(['err' => '1', 'msg' => '参数错误，无法执行']);
        }
        $dictType = strtolower($data['dicttype']);
        unset($data['dicttype']);
        if(!isset($data['name']) || $data['name'] == '')
        {
            return json(['err' => '2', 'msg' => '必须输入一个名称']);
        }
        if(!isset($data['spec']) || $data['spec'] == '')
        {
            return json(['err' => '3', 'msg' => '必须输入规格']);
        }
        if(!isset($data['price']) || $data['price'] == '')
        {
            return json(['err' => '5', 'msg' => '必须输入零售价']);
        }
        try
        {
            $info = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where([
                'id' => intval($data['id']), 'clinic_id' => $this->admin['clinic_id']
            ])->find();
            unset($data['id']);
            if($info) //数据已存在
            {
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where(['id' => $info['id']])->update($data);
            }else{ //数据不存在
                $sqlData = array_merge($data,[
                    'drugs_type' => '1', //类型,0=西药,1=中药,2=材料
                    'clinic_id' => $this->admin['clinic_id'], //诊所门店表的id
                    'remarks' => '', //备注
                    'create_time' => time(), //创建时间
                ]);
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->insertGetId($sqlData);
            }
            unset($data,$info,$sqlData);
            if(!$editRes) return json(['err' => '2', 'msg' => '中药数据保存失败']);
            return json(['err' => '0', 'msg' => '中药数据已保存成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '失败：' . $e->getMessage()]);
        }
    }
    //材料数据--修改+增加
    private function caiLiaoListInfo()
    {
        $data = $this->request->only([
            'dicttype','id','name','spec','changjia','cate_id','py_code','wb_code','bianma',
            'chandi','is_tscl','status','ls_unit','kc_unit','kc_zh_bi','price','max_price',
        ],'post');
        if(!isset($data['id']))
        {
            return json(['err' => '1', 'msg' => '参数错误，无法执行']);
        }
        $dictType = strtolower($data['dicttype']);
        unset($data['dicttype']);
        if(!isset($data['name']) || $data['name'] == '')
        {
            return json(['err' => '2', 'msg' => '必须输入一个名称']);
        }
        if(!isset($data['spec']) || $data['spec'] == '')
        {
            return json(['err' => '3', 'msg' => '必须输入规格']);
        }
        if(!isset($data['price']) || $data['price'] == '')
        {
            return json(['err' => '5', 'msg' => '必须输入零售价']);
        }
        try
        {
            $info = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where([
                'id' => intval($data['id']), 'clinic_id' => $this->admin['clinic_id']
            ])->find();
            unset($data['id']);
            if($info) //数据已存在
            {
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where(['id' => $info['id']])->update($data);
            }else{ //数据不存在
                $sqlData = array_merge($data,[
                    'drugs_type' => '2', //类型,0=西药,1=中药,2=材料
                    'clinic_id' => $this->admin['clinic_id'], //诊所门店表的id
                    'remarks' => '', //备注
                    'create_time' => time(), //创建时间
                ]);
                $editRes = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->insertGetId($sqlData);
            }
            unset($data,$info,$sqlData);
            if(!$editRes) return json(['err' => '2', 'msg' => '材料数据保存失败']);
            return json(['err' => '0', 'msg' => '材料数据已保存成功']);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '失败：' . $e->getMessage()]);
        }
    }

    //搜索添加西药、中药、材料 index/dictionary.drugs/find_clinic_drug
    public function find_clinic_drug()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $data = $this->request->only(['keyword','limit','page'],'post');
            if(!isset($data['page']))
            {
                return json(['err' => '2', 'msg' => '参数错误，无法获取数据']);
            }
            //条件
            $map = [['clinic_id','=', $this->admin['clinic_id']],['status','=','1']];
            if(isset($data['keyword']) && $data['keyword'] != '')
            {
                $map[] = ['name|jd_name|bianma|py_code|wb_code|changjia','like','%' . $data['keyword'] . '%'];
            }
            $limit = intval($data['limit']) > 0 ? intval($data['limit']) : 20;
            $field = '*';
            $list = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_drugs')->where($map)->field($field)
                    ->order('id desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
            if (count($list) <= 0) {
                return json(['err' => '3', 'msg' => '当前页下无数据']);
            }
            $xy_zjunit_list = ClinicDict::getDrugsZhiJiUnitList(); //西药 - 制剂单位
            $xy_kcunit_list = ClinicDict::getDrugsKuCunUnitList(); //西药 - 库存单位
            $zy_kcunit_list = ClinicDict::getZhongYaoUnitList(); //中药(销售单位+库存单位)、材料(最小单位+库存单位)
            $res = ['err' => '0', 'page' => $data['page'], 'limit' => $limit, 'data' => $list->items()];
            foreach ($res['data'] as $key => &$val) {
                //类型,0=西药,1=中药,2=材料
                if($val['drugs_type'] == 0) //西药
                {
                    $val['ls_unit'] = _getDictNameTxt($val['kc_unit'],$xy_kcunit_list);
                    if((int)$val['is_cl'] > 0)
                    {
                        $val['price'] = $val['cl_price'];
                        $val['ls_unit'] = _getDictNameTxt($val['zj_unit'],$xy_zjunit_list);
                    }
                    $val['spec'] = _getXiYaoSpecText($val);
                }
                //中药
                if($val['drugs_type'] == 1)
                {
                    $val['ls_unit'] = _getDictNameTxt($val['ls_unit'],$xy_zjunit_list);
                }
                //材料
                if($val['drugs_type'] == 2)
                {
                    $val['ls_unit'] = _getDictNameTxt($val['ls_unit'],$zy_kcunit_list);
                }
            }
            return json($res);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }

}
